package com.qy.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qy.service.WxService;

@WebServlet("/api")
public class WxServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("请求到达了");
		//取出微信服务器传过来的参数
		String signature = req.getParameter("signature");
		String timestamp = req.getParameter("timestamp");
		String nonce = req.getParameter("nonce");
		String echostr = req.getParameter("echostr");
		boolean success = WxService.check(timestamp, nonce, signature);
		if(success){
			System.out.println("接入成功");
			PrintWriter writer = resp.getWriter();
			writer.write(echostr);//接入成功需要原样返回echostr
		}else{
			System.out.println("接入失败");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置编码格式,不然中文会乱码
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
        //将请求中的xml参数转成map
		Map<String,String> map = WxService.parseRequest(req.getInputStream());
		System.out.println(map);
        //处理完将响应一个xml给微信
		String respXml = WxService.getRespose(map);
		System.out.println(respXml);
		resp.getWriter().print(respXml);
	}
}
